<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use fast\Random;
use think\Db;
use addons\shopro\library\traits\ActivityCache;
use addons\shopro\library\traits\Groupon;


class Login extends Api
{
    use ActivityCache,Groupon;

    protected $noNeedLogin = ['getZiJieMiniProgramSessionKey','ziJieMiniProgramOauth','lng_lat_address'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * POST 获取抖音小程序session_key
     * @param code 抖音小程序登录凭证
     * @author Ripple
     */
    public function getZiJieMiniProgramSessionKey(){
        if (!$this->request->isPost()){
            $this->error('非法请求');
        }

        $code = $this->request->post('code','');
        if ($code == ''){
            $this->error('登录凭证缺失');
        }

        //获取抖音小程序配置
        $ziJie = Db::name('shopro_config')->where(['name'=>'ziJieMiniProgram','group'=>'platform'])->value('value');
        $ziJie_array = json_decode($ziJie,true);
        $appid = isset($ziJie_array['appid']) ? $ziJie_array['appid']:'';
        $secret = isset($ziJie_array['secret']) ? $ziJie_array['secret']:'';
        //组装路径
        $baseUrl = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
        $param_data = [
            'appid' => $appid,
            'secret' => $secret,
            'anonymous_code' => '',
            'code' => $code
        ];
        //请求
        $result = curlPost($baseUrl,json_encode($param_data),['Content-Type: application/json']);
        //判断数据
        $result_array = json_decode($result,true);
        if (!isset($result_array['err_no']) || ($result_array['err_no'] != 0)){
            $this->error('授权登录出错',$result_array);
        }

        $session_key = $result_array['data']['session_key'];
        $openid = $result_array['data']['openid'];
        $unionid = $result_array['data']['unionid'];

        //判断是否已经登陆了
        $check_user_oauth = Db::name('shopro_user_oauth')->where([
            'provider' => 'ZiJie',
            'platform' => 'ziJieMiniProgram',
            'openid' => $openid,
            'user_id' => ['neq', 0]
        ])->find();
        if (!empty($check_user_oauth)){
            Db::name('shopro_user_oauth')->where(['id'=>$check_user_oauth['id']])->update(['session_key' => $session_key,'unionid' => $unionid]);

            $ret = $this->auth->direct($check_user_oauth['user_id']);
            if ($ret) {
                $token = $this->auth->getToken();
                $this->success('登录成功', ['token' => $token, 'session_key' => $session_key, 'openid' => $openid]);
            } else {
                $this->error($this->auth->getError());
            }
        }else{
            $this->success('获取成功',['session_key' => $session_key, 'openid' => $openid,'unionid'=>$unionid]);
        }

    }


    /**
     * POST 抖音小程序授权登录
     * @param openid openid
     * @param unionid unionid
     * @param session_key session_key
     * @param iv 手机号加密偏凉
     * @param encryptedData 手机号加密数据
     * @param avatarUrl 头像
     * @param nickName 昵称
     * @author Ripple
     */
    public function ziJieMiniProgramOauth(){
        if (!$this->request->isPost()){
            $this->error('非法请求');
        }

        $openid = $this->request->post('openid','');
        $unionid = $this->request->post('unionid','');
        $session_key = $this->request->post('session_key');
        $iv = $this->request->post('iv');//手机号加密偏凉
        $encryptedData = $this->request->post('encryptedData');//手机号加密数据
        $avatarUrl = $this->request->post('avatarUrl','');//头像
        $nickName = $this->request->post('nickName','');//昵称



        if (empty($openid) || empty($session_key) || empty($iv) || empty($encryptedData)){
            $this->error('参数缺失');
        }

        //解密手机号
        $aesKey       = base64_decode($session_key);
        $aesIV        = base64_decode($iv);
        $aesCipher    = base64_decode($encryptedData);
        $result       = json_decode(openssl_decrypt($aesCipher , "AES-128-CBC" , $aesKey , 1 , $aesIV),true);
        if (!isset($result['phoneNumber'])){
            $this->error('手机号解密出错');
        }
        $mobile = $result['phoneNumber'];


        //判断第三方授权信息
        $check_user_oauth = Db::name('shopro_user_oauth')->where([
            'provider' => 'ZiJie',
            'platform' => 'ziJieMiniProgram',
            'openid' => $openid
        ])->find();
        if (empty($check_user_oauth)){//首次授权
            //插入新的第三方授权信息
            $user_oauth = [
                'provider' => 'ZiJie',
                'platform' => 'ziJieMiniProgram',
                'unionid' => $unionid,
                'openid' => $openid,
                'nickname' => $nickName,
                'headimgurl' => $avatarUrl,
                'logintime' => time(),
                'logincount' => 1,
                'session_key' => $session_key,
                'createtime' => time(),
                'updatetime' => time(),
            ];
            Db::name('shopro_user_oauth')->insert($user_oauth);
            $user_oauth_id = Db::name('shopro_user_oauth')->getLastInsID();
            //创建新用户
            $username = Random::alnum(20);
            $password = '';
            $domain = request()->host();
            $extend = $this->getDefaultNickAvar();
            $extend['nickname'] = empty($nickName) ? $extend['nickname']:$nickName;
            $extend['avatar'] = empty($avatarUrl) ? $extend['avatar']:$avatarUrl;
            $this->auth->register($username, $password, $username . '@' . $domain, '', $extend);
            //更新用户昵称、来源、手机号
            $up_user = [
                'mobile' => $mobile,
                'user_source' => 2,
            ];
            if (empty($nickName)) {
                $up_user['nickname'] = $extend['nickname'] . $this->auth->getUser()->id;
            }
            $this->auth->getUser()->save($up_user);
            //更新第三方授权信息
            Db::name('shopro_user_oauth')->where(['id'=>$user_oauth_id])->update(['user_id'=>$this->auth->getUser()->id]);
        }else{//二次授权
            if (empty($check_user_oauth['user_id'])){//未绑定用户
                //更新第三方授权信息
                $up_user_oauth = [
                    'provider' => 'ZiJie',
                    'platform' => 'ziJieMiniProgram',
                    'unionid' => $unionid,
                    'openid' => $openid,
                    'nickname' => $nickName,
                    'headimgurl' => $avatarUrl,
                    'logintime' => time(),
                    'logincount' => $check_user_oauth['logincount'] + 1,
                    'session_key' => $session_key,
                    'updatetime' => time(),
                ];
                Db::name('shopro_user_oauth')->where(['id'=>$check_user_oauth['id']])->update($up_user_oauth);
                //创建新用户
                $username = Random::alnum(20);
                $password = '';
                $domain = request()->host();
                $extend = $this->getDefaultNickAvar();
                $extend['nickname'] = empty($nickName) ? $extend['nickname']:$nickName;
                $extend['avatar'] = empty($avatarUrl) ? $extend['avatar']:$avatarUrl;
                $this->auth->register($username, $password, $username . '@' . $domain, '', $extend);
                //更新用户昵称、来源、手机号
                $up_user = [
                    'mobile' => $mobile,
                    'user_source' => 2,
                ];
                if (empty($nickName)) {
                    $up_user['nickname'] = $extend['nickname'] . $this->auth->getUser()->id;
                }
                $this->auth->getUser()->save($up_user);
                //更新第三方授权信息
                Db::name('shopro_user_oauth')->where(['id'=>$check_user_oauth['id']])->update(['user_id'=>$this->auth->getUser()->id]);
            }else{//已绑定用户
                //判断用户是否存在
                $check_user = Db::name('user')->where(['id'=>$check_user_oauth['user_id']])->find();
                if (empty($check_user)){//用户被删除 重新创建
                    //创建新用户
                    $username = Random::alnum(20);
                    $password = '';
                    $domain = request()->host();
                    $extend = $this->getDefaultNickAvar();
                    $extend['nickname'] = empty($nickName) ? $extend['nickname']:$nickName;
                    $extend['avatar'] = empty($avatarUrl) ? $extend['avatar']:$avatarUrl;
                    $this->auth->register($username, $password, $username . '@' . $domain, '', $extend);
                    //更新用户昵称、来源、手机号
                    $up_user = [
                        'mobile' => $mobile,
                        'user_source' => 2,
                    ];
                    if (empty($nickName)) {
                        $up_user['nickname'] = $extend['nickname'] . $this->auth->getUser()->id;
                    }
                    $this->auth->getUser()->save($up_user);
                    //更新第三方授权信息
                    Db::name('shopro_user_oauth')->where(['id'=>$check_user_oauth['id']])->update(['user_id'=>$this->auth->getUser()->id]);
                }else{//用户正常存在
                    $up_user_oauth = [
                        'nickname' => $nickName,
                        'headimgurl' => $avatarUrl,
                        'logintime' => time(),
                        'logincount' => $check_user_oauth['logincount'] + 1,
                        'session_key' => $session_key,
                        'updatetime' => time(),
                    ];
                    Db::name('shopro_user_oauth')->where(['id'=>$check_user_oauth['id']])->update($up_user_oauth);
                    //更新用户昵称、头像、来源、手机号
                    $up_user = [
                        'mobile' => $mobile,
                        'user_source' => 2,
                    ];
                    $extend = $this->getDefaultNickAvar();
                    if (empty($check_user['nickname'])) {
                        $up_user['nickname'] = empty($nickName) ? $extend['nickname']:$nickName;
                    }
                    if (empty($check_user['avatar'])) {
                        $up_user['avatar'] = empty($avatarUrl) ? $extend['avatar']:$avatarUrl;
                    }
                    Db::name('user')->where(['id'=>$check_user['id']])->update($up_user);

                    $this->auth->direct($check_user['id']);
                }
            }
        }

        $token = $this->auth->getToken();

        $this->success('登录成功', ['token' => $token]);
    }


    /**
     * GET|POST 经纬度转换省市区
     * @param lng 经度
     * @param lat 维度
     * @author Ripple
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lng_lat_address(){
        $lng = $this->request->param('lng');
        $lat = $this->request->param('lat');

        //key用的是自己的，后期需要更改为客户的
        $url = 'https://restapi.amap.com/v3/geocode/regeo?key=621bb5513dc62866a503f2eac7357e27&location=' . $lng . ',' .$lat;
        $gaoDeData = json_decode(curlPost($url),true);

        //省市区处理
        $province = isset($gaoDeData['regeocode']['addressComponent']['province']) ? $gaoDeData['regeocode']['addressComponent']['province']:'';
        $city = isset($gaoDeData['regeocode']['addressComponent']['city']) ? $gaoDeData['regeocode']['addressComponent']['city']:$gaoDeData['regeocode']['addressComponent']['city'];
        $district = isset($gaoDeData['regeocode']['addressComponent']['district']) ? $gaoDeData['regeocode']['addressComponent']['district']:'';


        //市数据有几个特殊的没有
        switch ($province){
            case '北京市':
                $province_id = 110000;
                $city_id = 110100;//北京市
                $district_id = Db::name('shopro_area')->where(['level'=>3,'name'=>['like','%' . $district . '%']])->value('id');
                break;
            case '上海市':
                $province_id = 310000;
                $city_id = 310100;//上海市
                $district_id = Db::name('shopro_area')->where(['level'=>3,'name'=>['like','%' . $district . '%']])->value('id');
                break;
            case '天津市':
                $province_id = 120000;
                $city_id = 120100;//天津市
                $district_id = Db::name('shopro_area')->where(['level'=>3,'name'=>['like','%' . $district . '%']])->value('id');
                break;
            case '重庆市':
                $province_id = 500000;
                $city_id = '500100,500200';//重庆市、县
                $district_info = Db::name('shopro_area')->where(['level'=>3,'pid'=>['in',$city_id],'name'=>['like','%' . $district . '%']])->find();
                if (!empty($district_info)){
                    $city_id = $district_info['pid'];
                    $district_id = $district_info['id'];
                }else{
                    $city_id = 500100;//重庆市
                    $district_id = 0;
                }
                break;
            case '河南省':
                $province_id = 410000;
                if (empty($city)){
                    $city_id = 419000;//济源市
                    $district_id = 419001;//济源市
                }else{
                    $city_id = Db::name('shopro_area')->where(['pid'=>$province_id,'level'=>2,'name'=>['like','%' . $city . '%']])->value('id');
                    $district_id = Db::name('shopro_area')->where(['pid'=>$city_id,'level'=>3,'name'=>['like','%' . $district . '%']])->value('id');
                }
                break;
            case '湖北省':
                $province_id = 420000;
                if (empty($city)){
                    //仙桃市、潜江市、天门市、神农架林区
                    $city_id = 429000;//省直辖县级行政区划
                    $district_id = Db::name('shopro_area')->where(['pid'=>$city_id,'level'=>3,'name'=>['like','%' . $district . '%']])->value('id');
                }else{
                    $city_id = Db::name('shopro_area')->where(['pid'=>$province_id,'level'=>2,'name'=>['like','%' . $city . '%']])->value('id');
                    $district_id = Db::name('shopro_area')->where(['pid'=>$city_id,'level'=>3,'name'=>['like','%' . $district . '%']])->value('id');
                }
                break;
            case '海南省':
                $province_id = 460000;
                if (empty($city)){
                    //五指山市、文昌市、琼海市、万宁市、东方市、定安县、屯昌县、澄迈县、临高县、琼中黎族苗族自治县、保亭黎族苗族自治县、白沙黎族自治县、昌江黎族自治县、乐东黎族自治县、陵水黎族自治县
                    $city_id = 469000;//省直辖县级行政区划
                    $district_id = Db::name('shopro_area')->where(['pid'=>$city_id,'level'=>3,'name'=>['like','%' . $district . '%']])->value('id');
                }else{
                    $city_id = Db::name('shopro_area')->where(['pid'=>$province_id,'level'=>2,'name'=>['like','%' . $city . '%']])->value('id');
                    $district_id = Db::name('shopro_area')->where(['pid'=>$city_id,'level'=>3,'name'=>['like','%' . $district . '%']])->value('id');
                }
                break;
            case '新疆维吾尔自治区':
                $province_id = 650000;
                if (empty($city)){
                    //石河子市、阿拉尔市、图木舒克市、五家渠市、北屯市、铁门关市、双河市、可克达拉市、昆玉市
                    $city_id = 659000;//省直辖县级行政区划
                    $district_id = Db::name('shopro_area')->where(['pid'=>$city_id,'level'=>3,'name'=>['like','%' . $district . '%']])->value('id');
                }else{
                    $city_id = Db::name('shopro_area')->where(['pid'=>$province_id,'level'=>2,'name'=>['like','%' . $city . '%']])->value('id');
                    $district_id = Db::name('shopro_area')->where(['pid'=>$city_id,'level'=>3,'name'=>['like','%' . $district . '%']])->value('id');
                }
                break;
            default:
                //获取省id
                $province_id = Db::name('shopro_area')->where(['level'=>1,'name'=>['like','%' . $province . '%']])->value('id');
                //获取市id
                $city_id = Db::name('shopro_area')->where(['pid'=>$province_id,'level'=>2,'name'=>['like','%' . $city . '%']])->value('id');
                //获取区id
                $district_id = Db::name('shopro_area')->where(['pid'=>$city_id,'level'=>3,'name'=>['like','%' . $district . '%']])->value('id');
        }

        $province_id = intval($province_id);
        $city_id = intval($city_id);
        $district_id = intval($district_id);

        $result = [
            'province_id' => $province_id,
            'province_id_name' => Db::name('shopro_area')->where(['id'=>$province_id])->value('name'),
            'city_id' => $city_id,
            'city_id_name' => Db::name('shopro_area')->where(['id'=>$city_id])->value('name'),
            'district_id' => $district_id,
            'district_id_name' => Db::name('shopro_area')->where(['id'=>$district_id])->value('name'),
        ];

        $this->success('获取成功',$result);
    }


    /**
     * POST 大团长开团（大团长不参加）
     * @param activity_id 活动id
     * @param goods_id 商品id
     * @param goods_sku_price_id 商品规格配置id
     * @author Ripple
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function false_open_group(){
        if (!$this->request->isPost()){
            $this->error('非法请求');
        }

        $user_id = $this->auth->id;
        $activity_id = $this->request->post('activity_id');//活动id
        $goods_id = $this->request->post('goods_id');//商品id
        $goods_sku_price_id = $this->request->post('goods_sku_price_id');//商品规格id

        //获取用户信息
        $user_info = Db::name('user')->where(['id'=>$user_id])->find();

        //判断用户是否是大团长
        $check_group_identity = Db::name('shopro_group_identity')->where([
            'user_id' => $user_id,
            'activity_id'=>0,
            'activity_groupon_id'=>0,
            'level' => 1,
            'status' => 1,
        ])->find();
        if (empty($check_group_identity)){
            $this->error('您不是大团长！无法开团');
        }

        //验证活动
        $check_activity = Db::name('shopro_activity')->where(['id'=>$activity_id,'type'=>'groupon'])->find();
        if (empty($check_activity)){
            $this->error('活动不存在');
        }
        if ($check_activity['endtime'] < time()){
            $this->error('活动已结束');
        }
        //验证活动规则
        $rules = json_decode($check_activity['rules'],true);
        if (!(isset($rules['not_participate']) && $rules['not_participate'])){
            $this->error('活动不允许大团长只开团不参团');
        }
        $goods_ids_array = explode(',',$check_activity['goods_ids']);
        if (!in_array($goods_id,$goods_ids_array)){
            $this->error('活动商品不存在');
        }
        //验证商品规格
        $check_goods_sku_price = Db::name('shopro_activity_goods_sku_price')->where([
            'activity_id' => $check_activity['id'],
            'sku_price_id' => $goods_sku_price_id,
            'goods_id' => $goods_id,
            'status' => 'up',
        ])->find();
        if (empty($check_goods_sku_price)){
            $this->error('商品规格未参加活动');
        }

        //判断拼团次数
        if (isset($rules['limit_opening_times'])){
            $rules['limit_opening_times'] = intval($rules['limit_opening_times']);
            $opening_times = Db::name('shopro_activity_groupon')->where(['user_id'=>$user_id])->count();
            if (($rules['limit_opening_times'] > 0) && ($opening_times >= $rules['limit_opening_times'])){
                $this->error('该活动单人限制开团次数为' . $rules['limit_opening_times'] . ',您已经达到上限');
            }
        }


        Db::startTrans();

        //增加团记录
        $expiretime = empty($rules['valid_time']) ? 0: ($rules['valid_time']*3600);
        $groupon_data = [
            'user_id' => $user_id,
            'goods_id' => $goods_id,
            'activity_id' => $check_activity['id'],
            'num' => $rules['team_num'],//成团人数
            'current_num' => 0,//当前人数
            'status' => 'ing',
            'expiretime' => $expiretime,
            'createtime' => null,
            'updatetime' => null,
            'active_team_num' => $rules['team_num'],
        ];
        $result = Db::name('shopro_activity_groupon')->insert($groupon_data);
        if ($result === false){
            Db::rollback();
            $this->error('系统繁忙！请稍后再试');
        }
        $groupon_id = Db::name('shopro_activity_groupon')->getLastInsID();
        //增加团员记录
        $groupon_log_data = [
            'user_id' => $user_id,
            'user_nickname' => isset($user_info['nickname']) ? $user_info['nickname']:'',
            'user_avatar' => isset($user_info['avatar']) ? $user_info['avatar']:'',
            'groupon_id' => $groupon_id,
            'goods_id' => $goods_id,
            'goods_sku_price_id' => $goods_sku_price_id,
            'activity_id' => $check_activity['id'],
            'is_leader' => 1,
            'is_fictitious' => 0,
            'order_id' => 0,
            'is_refund' => 0,
            'createtime' => time(),
            'updatetime' => time(),
        ];
        $result = Db::name('shopro_activity_groupon_log')->insert($groupon_log_data);
        if ($result === false){
            Db::rollback();
            $this->error('系统繁忙！请稍后再试');
        }

        $goods_item['activity_id'] = $check_activity['id'];
        $goods_item['goods_id'] = $goods_id;
        $order['id'] = 0;
        $this->joinGrouponIdentity($goods_item,$groupon_id,$order,$user_id);

        //无上限团增加虚拟人数
        if ($rules['team_num'] == 0){
            //获取活动详情
            $check_activity_rules = json_decode($check_activity['rules'],true);
            if (isset($check_activity_rules['virtual_number']) && (intval($check_activity_rules['virtual_number']) > 0)){
                $virtual_number = intval($check_activity_rules['virtual_number']);
                // 查询虚拟用户
                $userFakes = Db::name('shopro_user_fake')->orderRaw('rand()')->limit($virtual_number)->select();
                //虚拟人数够
                if (count($userFakes) == $virtual_number) {
                    // 增加团人数
                    Db::name('shopro_activity_groupon')->where(['id'=>$groupon_id])->update(['current_num'=>$virtual_number]);
                    for ($i = 0; $i < $virtual_number; $i ++) {
                        // 增加参团记录
                        $groupon_log_data = [
                            'user_id' => 0,
                            'user_nickname' => $userFakes[$i]['nickname'],
                            'user_avatar' => $userFakes[$i]['avatar'],
                            'groupon_id' => $groupon_id,
                            'goods_id' => $groupon_data['goods_id'],
                            'goods_sku_price_id' => 0,
                            'activity_id' => $groupon_data['activity_id'],
                            'is_leader' => 0,
                            'is_fictitious' => 1,
                            'order_id' => 0,
                            'is_refund' => 0,
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                        $result = Db::name('shopro_activity_groupon_log')->insert($groupon_log_data);
                        if ($result === false){
                            Db::rollback();
                            $this->error('系统繁忙！请稍后再试');
                        }

                        //更新redis
                        if ($this->hasRedis()) {
                            $keys = $this->getKeys([
                                'groupon_id' => $groupon_id,
                                'goods_id' => $groupon_data['goods_id'],
                            ], [
                                'activity_id' => $check_activity['id'],
                                'activity_type' => $check_activity['type'],
                            ]);

                            extract($keys);

                            $redis = $this->getRedis();
                            // 当前团人数 grouponNumKey 如果不存在，自动创建
                            $redis->HINCRBY($activityHashKey, $grouponNumKey, 1);
                        }

                    }

                }
            }
        }

        Db::commit();

        if ($expiretime > 0) {
            // 增加自动关闭拼团队列(如果有虚拟成团，会判断虚拟成团)
            \think\Queue::later($expiretime, '\addons\shopro\job\ActivityGrouponAutoOper@expire', [
                'activity' => $check_activity,
                'activity_groupon_id' => $groupon_id
            ], 'shopro');
        }


        $this->success('开团成功',['groupon_id' => $groupon_id]);

    }
    public function joinGrouponIdentity($goods_item,$groupon_id, $order,$user_id) {


        //判断用户是否是大团长
        $check_group_identity = Db::name('shopro_group_identity')->where([
            'user_id' => $user_id,
            'activity_id'=>0,
            'activity_groupon_id'=>0,
            'level' => 1,
            'status' => 1,
        ])->find();

        if ($groupon_id && $check_group_identity) {

            $ddd = Db::name('shopro_activity_groupon_log')->where('groupon_id',$groupon_id)->count();
            if ($ddd==1){

//                file_put_contents("access_token.json",'1|'.json_encode($groupon_id).PHP_EOL, FILE_APPEND|LOCK_EX);
//                file_put_contents("access_token.json",'2|'.json_encode($goods_item['goods_id']).PHP_EOL, FILE_APPEND|LOCK_EX);

//                file_put_contents("access_token.json",'3|'.json_encode($order['id']).PHP_EOL, FILE_APPEND|LOCK_EX);
                $shopro_activity_goods_sku_price_info = Db::name('shopro_activity_goods_sku_price')
                    ->where('activity_id',$goods_item['activity_id'])
                    ->where('goods_id',$goods_item['goods_id'])
                    ->find();
//                file_put_contents("access_token.json",json_encode($shopro_activity_goods_sku_price_info).PHP_EOL, FILE_APPEND|LOCK_EX);
                $commission_type = 0;
                $commission_money = 0;
                $commission_bili = 0;
                if (!empty($shopro_activity_goods_sku_price_info['commission_money'])){
                    $commission_money = $shopro_activity_goods_sku_price_info['commission_money'];
                    $commission_type = 1;
                }else{
                    $commission_bili = $shopro_activity_goods_sku_price_info['commission_bili'];
                    $commission_type = 0;
                }
                $insert = array(
                    'activity_id' => $goods_item['activity_id'],
                    'activity_groupon_id' => $groupon_id,
                    'parent_user_id' => 0,
                    'order_id' => $order['id'],
                    'user_id' =>  $user_id,
                    'member_type'=>1,
                    'level' => 1,
                    'commission_type'=>$commission_type,
                    'commission_money'=>$commission_money,
                    'commission_bili'=>$commission_bili,
                    'createtime' => time()
                );

                $in = Db::name('shopro_group_identity')->insert($insert);
            }


            return true;
        }
    }


    /**
     * POST 团员申请拼团售后
     * @param groupon_id 团id
     * @author Ripple
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function group_after_sales(){
        if (!$this->request->isPost()){
            $this->error('非法请求');
        }

        $user_id = $this->auth->id;
        $groupon_id = $this->request->post('groupon_id');//拼团团id
        $application_remark = $this->request->post('application_remark','');//退团原因
        if (empty($groupon_id) || ($application_remark == '')){
            $this->error('参数缺失');
        }

        //判断团信息
        $check_groupon = Db::name('shopro_activity_groupon')
                            ->where(['id'=>$groupon_id])
                            ->find();
        if (empty($check_groupon)){
            $this->error('拼图信息不存在');
        }
        switch ($check_groupon['status']){
            case 'invalid'://已过期
                $this->error('拼团失败无法申请');
                break;
            case 'ing'://进行中
                $this->error('拼团进行中无法申请');
                break;
            case 'finish'://已成团
                break;
            case 'finish-fictitious'://虚拟成团
                break;
        }
        if ($check_groupon['user_id'] == $user_id){
            $this->error('团长无法申请');
        }
        //判断用户是否参团
        $check_groupon_log = Db::name('shopro_activity_groupon_log')
                                ->where([
                                    'user_id' => $user_id,
                                    'groupon_id' => $groupon_id,
                                ])->find();
        if (empty($check_groupon_log)){
            $this->error('未参团！无法申请');
        }


        //判断是否申请过
        $check_after_sale = Db::name('shopro_activity_groupon_after_sale')
                                ->where([
                                    'activity_groupon_id' => $check_groupon['id'],
                                    'user_id' => $user_id,
                                ])->find();
        if (empty($check_after_sale)){
            $up_data = [
                'application_remark' => $application_remark,
                'application_time' => time(),
                'processing_time' => 0,
                'processing_results' => 1,
                'processing_remark' => '',
                'updatetime' => time(),
            ];
            Db::name('shopro_activity_groupon_after_sale')
                ->where(['id'=>$check_after_sale['id']])
                ->update($up_data);
        }else{
            $insert_data = [
                'activity_groupon_id' => $check_groupon['id'],
                'user_id' => $user_id,
                'application_remark' => $application_remark,
                'application_time' => time(),
                'processing_time' => 0,
                'processing_results' => 1,
                'processing_remark' => '',
                'createtime' => time(),
                'updatetime' => time(),
            ];
            Db::name('shopro_activity_groupon_after_sale')->insert($insert_data);
        }

        $this->success('申请成功！请耐心等待团长审核');


    }


    /**
     * POST 团长处理售后申请
     * @param groupon_after_sale_id 拼团售后申请id
     * @param operation 操作 2：同意 3：拒绝
     * @param processing_remark 拒绝理由
     * @author Ripple
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function deal_after_sales(){
        if (!$this->request->isPost()){
            $this->error('非法请求');
        }

        $user_id = $this->auth->id;
        $groupon_after_sale_id = $this->request->post('groupon_after_sale_id');//拼团售后申请id
        $operation = $this->request->post('operation');//操作 2：同意 3：拒绝
        $processing_remark = $this->request->post('processing_remark','');//拒绝理由
        if (empty($groupon_after_sale_id) || !in_array($operation,['2','3'])){
            $this->error('参数缺失');
        }

        //检查售后记录是否存在
        $check_after_sale = Db::name('shopro_activity_groupon_after_sale')->where(['id'=>$groupon_after_sale_id])->find();
        if (empty($check_after_sale)){
            $this->error('售后申请信息不存在');
        }
        switch ($check_after_sale['processing_results']){
            case '1'://待处理
                break;
            case '2'://已同意
                $this->error('已处理！无需再次请求');
                break;
            case '3'://已拒绝
                $this->error('已处理！无需再次请求');
                break;
        }
        //判断用户是否是团长
        $check_groupon = Db::name('shopro_activity_groupon')
            ->where(['id'=>$check_after_sale['activity_groupon_id']])
            ->find();
        if (empty($check_groupon)){
            $this->error('拼图信息不存在');
        }
        switch ($check_groupon['status']){
            case 'invalid'://已过期
                $this->error('拼团失败无需处理');
                break;
            case 'ing'://进行中
                $this->error('拼团进行中无需处理');
                break;
            case 'finish'://已成团
                break;
            case 'finish-fictitious'://虚拟成团
                break;
        }
        if ($check_groupon['user_id'] != $user_id){
            $this->error('非团长无法处理');
        }

        //处理
        switch ($operation){
            case '2'://同意
                $model = new \app\admin\model\shopro\activity\Groupon;
                $row = $model->where('id', $check_groupon['id'])->find();

                // 解散团，并退款
                $this->invalidRefundGroupon($row);
                break;
            case '3'://拒绝
                if ($processing_remark == ''){
                    $this->error('请填写拒绝理由');
                }
                Db::name('shopro_activity_groupon_after_sale')->where([
                    'id' => $check_after_sale['id']
                ])->update([
                    'processing_time' => time(),
                    'processing_results' => 3,
                    'processing_remark' => $processing_remark,
                    'updatetime' => time(),
                ]);
                break;
        }

        $this->success('处理成功');
    }


    //获取默认头像 昵称
    private function getDefaultNickAvar(){
        $userConfig = json_decode(\addons\shopro\model\Config::get(['name' => 'user'])->value, true);
        return $userConfig;
    }

}
